<!-- 产线能力弹窗 -->

<template>
  <el-dialog append-to-body :title="productionLineCapacity.title" :visible.sync="productionLineCapacity.visible" @close="close" width="60%" top="5vh">
    <avue-crud
      v-model="form"
      ref="crud"
      :option="option"
      :table-loading="loading"
      :data="data"
      :defaults.sync="defaults"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      @row-del="rowDel"
      @current-change="currentChange"
      @size-change="sizeChange"
      @on-load="onLoad"
    >
      <template slot="tpcHeader" slot-scope="{ column }">
        <el-tooltip class="item" effect="dark" placement="top-start">
          <i class="el-icon-info" style="color: #606266"></i>
          <div slot="content">TPC（Total Production Cycle）指该产线生产一个完整产品所需时间（单位：分钟）</div>
        </el-tooltip>
        <span>&nbsp;{{ column.label }}</span>
      </template>
      <template slot="uphHeader" slot-scope="{ column }">
        <el-tooltip class="item" effect="dark" placement="top-start">
          <i class="el-icon-info" style="color: #606266"></i>
          <div slot="content">UPH（units per hour）指该产线生产该产品的单位小时产能，即每小时的产量</div>
        </el-tooltip>
        <span>&nbsp;{{ column.label }}</span>
      </template>
      <template slot="processRouteVosHeader" slot-scope="{ column }">
        <el-tooltip class="item" effect="dark" placement="top-start">
          <i class="el-icon-info" style="color: #606266"></i>
          <div slot="content">以该工站的产出作为此产品在当前产线的产出</div>
        </el-tooltip>
        <span>&nbsp;{{ column.label }}</span>
      </template>
      <template slot="partNameSearch">
        <el-input disabled placeholder="请输入产品名称">
          <el-button slot="append" icon="el-icon-search" @click="openCommonModal"></el-button>
        </el-input>
      </template>
      <template slot-scope="{ row }" slot="uph">
        <el-input-number size="mini" style="width: 105px" v-model="row.uph" controls-position="right" :min="0"> </el-input-number>
      </template>
      <template slot-scope="{ row }" slot="tpc">
        <el-input-number size="mini" style="width: 105px" v-model="row.tpc" controls-position="right" :min="0"> </el-input-number>
      </template>
      <template slot-scope="{ row, index }" slot="processRouteVos">
        <el-select v-model="row.routeId" @change="changeEvent(row, index)">
          <el-option v-for="item in row.processRouteVos" :key="item.id" :label="item.routeName" border="none" :value="item.id"> </el-option>
        </el-select>
      </template>
    </avue-crud>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" type="primary" @click="submitForm" icon="el-icon-circle-plus-outline">保 存 </el-button>
      <el-button size="small" @click="close" icon="el-icon-circle-close">取 消</el-button>
    </div>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" :key="timer" @newKey="newKey" @getSelectedRows="getSelectedRows"> </common-modal-template>
  </el-dialog>
</template>

<script>
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { getListLineproducts, addLineproducts, removeLineproducts, getProcessRoute } from '@/api/product/productionline';
export default {
  name: 'productionLineCapacityModal',
  components: {
    CommonModalTemplate
  },
  props: {
    config: {
      require: true,
      default: () => {}
    }
  },
  watch: {
    config: {
      handler(val) {
        this.productionLineCapacity.visible = val.visible;
      },
      deep: true
    }
  },
  mounted() {
    this.productionLineCapacity.visible = this.config.visible;
  },
  data() {
    return {
      lineId: null,
      productionLineCapacity: {
        title: '产线能力',
        visible: false,
        form: {
          production: ''
        }
      },
      data: [],
      // 产线配置页 crud
      option: {
        height: '450',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: false,
        excelBtn: false, // 导出
        delBtn: true,
        editBtn: false,
        addBtn: false,
        refreshBtn: false,
        selection: false,
        dialogClickModal: false,
        labelWidth: 120,
        menuWidth: 150,
        filterBtn: false,
        filters: false,
        columnBtn: false,
        label: '选择产品',
        icon: 'el-icon-vertical-bar',
        arrow: false,
        searchBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '产品名称',
            prop: 'partName',
            search: true,
            type: 'search'
            // appendClick: () => {
            //   this.openCommonModal();
            // }
          },
          {
            label: '产品编码',
            prop: 'partNo'
          },
          {
            label: '产品类型',
            prop: 'categoryName'
          },
          {
            label: '产线产出统计工站',
            prop: 'processRouteVos',
            slot: true,
            headerslot: true
          },
          // { label: 'UPH', prop: 'uph', type: 'number', slot: true, headerslot: true },
          { label: 'TPC', prop: 'tpc', type: 'number', slot: true, headerslot: true },
          {
            label: '添加时间',
            prop: 'createTime'
          }
        ]
      },
      headerFormOption: {
        labelWidth: 80,
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '选择产品',
            prop: 'name',
            type: 'search',
            disabled: true,
            span: 24
          }
        ]
      },
      timer: new Date().getTime(),
      tableOption: {}
    };
  },
  methods: {
    async showDialog(lineId) {
      this.data = [];
      this.lineId = lineId;
      this.productionLineCapacity.visible = true;
      await getListLineproducts(lineId)
        .then((res) => {
          if (res && res.status == 200) {
            let data = res.data.data;
            data.forEach(async (element) => {
              element.isDelete = true;
              let routeRes = await getProcessRoute(this._get(element, 'partNo', ''));
              let routes = routeRes.data.data || [];
              this.$set(element, 'processRouteVos', routes);
            });
            this.data = data;
          }
        })
        .catch((err) => {});
    },
    // 配置产线可生产的产品
    submitForm() {
      let status = this.data.every((d) => {
        return (d.tpc || d.tpc == 0) && (d.uph || d.uph == 0);
      });
      if (!status) {
        this.$message.warning('TPC和UPH不能为空');
        return;
      }
      let data = this.data.map((d) => {
        return {
          id: d.id,
          lineId: this.lineId,
          partNo: d.partNo,
          productId: d.productId,
          tpc: d.tpc + '',
          uph: d.uph + '',
          routeId: d.routeId
        };
      });
      addLineproducts(data)
        .then((res) => {
          if (res && res.status == 200) {
            this.$message.success('当前产线配置可生产产品成功');
            this.close();
          }
        })
        .catch((err) => {});
    },
    changeEvent(val, index) {
      this.data.forEach((element, i) => {
        if (i === index) {
          element.routeId = val.routeId;
        }
      });
    },
    close() {
      this.productionLineCapacity.visible = false;
      this.$emit('close');
    },
    /**
     * 打开模态框
     */
    openCommonModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择产品信息',
        url: '/api/mes-admin/part-master/page',
        isPage: true,
        query: {
          semifinished: true
        },
        // rowSelectionType: 'single',
        rowSelectionType: 'multiple',
        columnDefs: [
          {
            label: '类别',
            prop: 'categoryId',
            search: true,
            type: 'tree',
            dicUrl: '/api/mes-admin/part-category/tree',
            props: {
              label: 'title',
              value: 'id'
            }
          },
          {
            label: '编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '型号',
            prop: 'partModel'
          },
          {
            label: '描述',
            prop: 'description'
          },
          {
            label: '版本',
            prop: 'revision'
          },
          {
            label: '仓库物料类别',
            prop: 'partType',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=part_type'
          }
        ]
      };
    },
    // 获取选择的模态框行数据
    getSelectedRows(rowData) {
      if (Array.isArray(rowData)) {
        let result = rowData.map((row) => {
          return {
            categoryName: row['$categoryId'],
            partName: row['name'],
            partNo: row['partNo'],
            productId: row['id'],
            createTime: row['createTime'],
            tpc: row['tpc'],
            uph: row['uph']
          };
        });
        let setResult = result.filter((r) => {
          return !this.data.map((d) => d.productId).includes(r.productId);
        });
        let data = this.data.concat(setResult);
        data.forEach(async (element) => {
          if (!this._get(element, 'processRouteVos', '')) {
            let routeRes = await getProcessRoute(this._get(element, 'partNo', ''));
            let routes = routeRes.data.data || [];
            this.$set(element, 'processRouteVos', routes);
          }
        });
        this.data = data;
        // 多选
      } else {
        // 单选
        let categoryName = this._get(rowData, '$categoryId', '');
        let partName = this._get(rowData, 'name', '');
        let partNo = this._get(rowData, 'partNo', '');
        let productId = this._get(rowData, 'id', '');
        let createTime = this._get(rowData, 'createTime', '');
        let tpc = this._get(rowData, 'tpc', '');
        let uph = this._get(rowData, 'uph', '');
        let isFind = this.data.find((d) => d.productId == rowData.id);
        if (!isFind) {
          this.data.push({
            productId,
            categoryName,
            partName,
            partNo,
            tpc,
            uph,
            createTime,
            isDelete: false
          });
        }
      }
    },
    beforeOpen(done, type) {
      if (['edit'].includes(type)) {
        this.defaults.partName.display = false;
        this.defaults.partNo.display = false;
        this.defaults.partType.display = false;
        this.defaults.createTime.display = false;
      }
      done();
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let param = {
          lineId: this.lineId,
          productIdList: [row.productId]
        };
        if (row.isDelete) {
          removeLineproducts(param)
            .then((res) => {
              if (res && res.status == 200) {
                let findIndex = this.data.findIndex((d) => d.productId == row.productId);
                this.data.splice(findIndex, 1);
                this.$message({
                  type: 'success',
                  message: '操作成功!'
                });
              }
            })
            .catch((err) => {});
        } else {
          let findIndex = this.data.findIndex((d) => d.productId == row.productId);
          this.data.splice(findIndex, 1);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        }
      });
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style></style>
